package com.petmarket.common;

import com.petmarket.contract.UserContract;
import com.petmarket.uitls.SpringUtils;
import lombok.Getter;
import org.fisco.bcos.sdk.jni.common.JniException;
import org.fisco.bcos.sdk.v3.BcosSDK;
import org.fisco.bcos.sdk.v3.client.Client;
import org.fisco.bcos.sdk.v3.codec.ContractCodec;
import org.fisco.bcos.sdk.v3.codec.ContractCodecException;
import org.fisco.bcos.sdk.v3.crypto.signature.SignatureResult;
import org.fisco.bcos.sdk.v3.model.TransactionReceipt;
import org.fisco.bcos.sdk.v3.transaction.manager.transactionv1.ProxySignTransactionManager;
import org.fisco.bcos.sdk.v3.transaction.manager.transactionv1.dto.AbiEncodedRequest;
import org.fisco.bcos.sdk.v3.transaction.manager.transactionv1.utils.TransactionRequestBuilder;
import org.fisco.bcos.sdk.v3.transaction.model.exception.ContractException;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;


public  class TransactionManager {

    @Getter
    private static BcosSDK sdk = SpringUtils.getBean("bcosSDK");
    @Getter
    private static Client client=sdk.getClient();


    public static void sendTransaction(String contractName,  BcosSDK sdk,String hexPrivateKey) throws JniException, ContractCodecException, ContractException {
//        // 初始化SDK和Client
//        BcosSDK sdk = BcosSDK.build(CONFIG_FILE);
//        Client client = sdk.getClient("group0");

        // 为群组初始化client
        Client client = getClient();

// 初始化ProxySignTransactionManager
        ProxySignTransactionManager proxySignTransactionManager;
// ProxySignTransactionManager可以接受AsyncTransactionSignercInterface的实现作为构造函数参数
        proxySignTransactionManager = new ProxySignTransactionManager(client, (hash, transactionSignCallback) -> {
            SignatureResult sign = client.getCryptoSuite().sign(hash, client.getCryptoSuite().getCryptoKeyPair());
            transactionSignCallback.handleSignedTransaction(sign);
        });


        ContractCodec contractCodec=new ContractCodec(client.getCryptoSuite(),false);

       List<Object>params=new ArrayList<>();
       params.add(1);
       params.add("123123");
       params.add("123123");
       params.add("1");

// 对合约参数进行编解码
        byte[] abiEncoded = contractCodec.encodeMethod(UserContract.getABI(), "insert", params);

// 采用链式构造AbiEncodedRequest，传入contractAddress、nonce、blockLimit等重要参数，最后使用buildAbiEncodedRequest结束构造。
        AbiEncodedRequest request =
                new TransactionRequestBuilder()
                        .setTo(CommonClient.getContractAddress(contractName))
                        .setAbi(UserContract.getABI())
                        .setBlockLimit(BigInteger.valueOf(2000))
                        .setExtension("Hello World".getBytes())
                        .setGasPrice(BigInteger.TEN)
                        .buildAbiEncodedRequest(abiEncoded);

// 同步发送上链，获得回执
        TransactionReceipt receipt = proxySignTransactionManager.sendTransaction(request);

    }

}
